package org.catdroid.spora.html;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;


public class GetHtmlContent
{
	// TagNode object, its use will come in later
	TagNode		page;
	Object[]	nodes;
	int			currentNode;

	public GetHtmlContent(String urlAddress) throws IOException
	{
		// this is where the HtmlCleaner comes in, I initialize it here
		HtmlCleaner cleaner = new HtmlCleaner();
		CleanerProperties props = cleaner.getProperties();
		props.setAllowHtmlInsideAttributes(true);
		props.setAllowMultiWordAttributes(true);
		props.setRecognizeUnicodeChars(true);
		props.setOmitComments(true);

		// open a connection to the desired URL
		URL url = new URL(urlAddress);
		URLConnection conn = url.openConnection();

		// use the cleaner to "clean" the HTML and return it as a TagNode object
		page = cleaner.clean(new InputStreamReader(conn.getInputStream(), "UTF-8"));
	}

	// Returns the first node recovered by the xPath
	public String getText(String xPath) throws XPatherException
	{

		nodes = page.evaluateXPath(xPath);
		if (nodes.length > 0)
		{
			String info;
			// casted to a TagNode
			try
			{
				info = new HtmlCleaner().getInnerHtml((TagNode) nodes[0]).trim();
				// info =
				// info_node.getChildren().iterator().next().toString().trim();
			}
			catch (Exception e)
			{
				info = (String) nodes[0];
			}

			// how to retrieve the contents as a string

			currentNode = 1;
			return info;
		}
		else
		{
			return "";
		}
	}

	public String[] getTextArray(String xPath) throws XPatherException
	{
		ArrayList<String> items = new ArrayList<String>();
		Object[] nodes = getNodes(xPath);
		for (Object nodeObject : nodes)
		{
			((TagNode) nodeObject).getText().toString();
		}
		return items.toArray(new String[items.size()]);
	}

	public Object[] getNodes(String xPath) throws XPatherException
	{
		return page.evaluateXPath(xPath);
	}

	public Object getContent(String xPath) throws XPatherException, IOException
	{
		String address = getText(xPath);
		URL url = new URL(address);
		return url.getContent();
	}

}
